package com.example.myapplication

import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*

/**
 * Created by zpf on 12/27/20.
 */
object MD5Utils {

    fun md5(str: String): String {
        val digest = MessageDigest.getInstance("MD5")
        val result = digest.digest(str.toByteArray())
        //1632
        return toHex(result)
    }

    fun toHex(byteArray: ByteArray): String {
        val result = with(StringBuilder()) {
            byteArray.forEach {
                val hex = it.toInt() and (0xFF)
                val hexStr = Integer.toHexString(hex)
                if (hexStr.length == 1) {
                    this.append("0").append(hexStr)
                } else {
                    this.append(hexStr)
                }
            }
            this.toString()
        }
        //1632
        return result
    }

    fun sha1(str: String): String {
        val digest = MessageDigest.getInstance("SHA-1")
        val result = digest.digest(str.toByteArray())
        return toHex(result)
    }

    fun sha256(str: String): String {
        val digest = MessageDigest.getInstance("SHA-256")
        val result = digest.digest(str.toByteArray())
        return toHex(result)
    }

    // 1000 * sha1(lower(deviceid) + md5(appid))
    fun encryption(deviceid: String, appid: String): String {
        var securedText: String = deviceid.toLowerCase(Locale.getDefault()) + md5(appid)
        for (i in 0..999) {
            securedText = sha1(securedText)
        }
        return securedText
    }

    fun encode(text: String): String {
        try {
            //md5
            val instance: MessageDigest = MessageDigest.getInstance("MD5")
            //，
            val digest: ByteArray = instance.digest(text.toByteArray())
            val sb = StringBuffer()
            for (b in digest) {
                //
                val i: Int = b.toInt() and 0xff
                //16
                var hexString = Integer.toHexString(i)
                if (hexString.length < 2) {
                    //，0
                    hexString = "0$hexString"
                }
                sb.append(hexString)
            }
            return sb.toString()

        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return text
    }
}